//
//  AECommunityPublishViewController.m
//  AESOLAR_IOS
//
//  Created by Bin Tang on 2024/10/18.
//  Copyright © 2024 Mr.Wang. All rights reserved.
//

#import "AECommunityPublishViewController.h"
#import "AE_Solar-Swift.h"
#import "AECommunityPublishViewModel.h"
#import "AECommunityPublishNavView.h"
#import "TYZPlaceholderTextView.h"
#import "DoImagePickerViewController.h"
#import "AuthorityManager.h"
#import "EDSPublishDynamicImageVideoView.h"
#import "DoImagePickerViewController.h"

@interface AECommunityPublishViewController () <UITextViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UITextFieldDelegate>

@property (nonatomic, strong) AECommunityPublishViewModel *viewModel;

@property (nonatomic, strong) AECommunityPublishNavView *navView;

/// 标题
@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) UITextField *txtTitleField;

/// 发布内容
@property (nonatomic, strong) TYZPlaceholderTextView *contentTextView;

/// 图片视图
@property (nonatomic, strong) EDSPublishDynamicImageVideoView *imageVideoView;

@end

@implementation AECommunityPublishViewController

- (void)dealloc {
    debugMethod();
    
}

- (void)initWithVar {
    [super initWithVar];
    
}

- (void)initWithViewModel {
    _viewModel = [AECommunityPublishViewModel new];
    _viewModel.reqModel.newsGroupId = self.newsGroupId;
    [_viewModel setupData];
}

- (void)initWithNavBar {
    [super initWithNavBar];
    
    [self initWithNavView];
    
}

- (void)initWithSubView {
    [super initWithSubView];
    
    self.view.backgroundColor = [UIColor colorWithHexString:@"#FAFAFA"];
    [self initWithRootContent:NO];
    self.rootContent.top = self.navView.bottom;
    self.rootContent.height = kScreenH - self.navView.bottom;
    self.rootContent.backgroundColor = [UIColor colorWithHexString:@"#FAFAFA"];
//    self.rootContent.userInteractionEnabled = YES;
    self.rootContent.delegate = self;
    
    [self initWithTitleLabel];
    
    [self initWithTxtTitleField];
    
    [self initWithContentTextView];
    
    [self initWithImageVideoView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

- (void)initWithNavView {
    if (!_navView) {
        CGRect frame = CGRectMake(0, 0, kScreenW, NAVBAR_HEIGHT_STATUS);
        _navView = [[AECommunityPublishNavView alloc] initWithFrame:frame];
        [self.view addSubview:_navView];
        @weakify(self);
        _navView.touchCancelBlock = ^{
            @strongify(self);
            [self actionWithCancel];
        };
        _navView.touchPublishBlock = ^{
            @strongify(self);
            [self actionWithPublish];
        };
    }
}

- (void)initWithTitleLabel {
    if (!_titleLabel) {
        CGRect frame = CGRectMake(15, 5, kScreenW - 30, 18);
        NSString *str = @"标题";
        UIFont *font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
        _titleLabel = [UILabel createWithLabel:self.rootContent frame:frame font:font propertiesBlock:^(UILabel * _Nonnull label) {
            label.textColor = [UIColor colorWithHexString:@"#333333"];
            label.text = str;
        }];
    }
}

- (void)initWithTxtTitleField {
    if (!_txtTitleField) {
        CGRect frame = CGRectMake(15, self.titleLabel.bottom + 5, kScreenW - 30, 32);
        _txtTitleField = [[UITextField alloc] initWithFrame:frame];
        _txtTitleField.placeholder = @"请输入标题";
//        _txtTitleField.textAlignment = NSTextAlignmentRight;
        _txtTitleField.textColor = [UIColor colorWithHexString:@"#333333"];
        _txtTitleField.font = [UIFont systemFontOfSize:16 weight:UIFontWeightRegular];
        _txtTitleField.borderStyle = UITextBorderStyleNone;
        _txtTitleField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _txtTitleField.returnKeyType = UIReturnKeyDone;
        _txtTitleField.delegate = self;
        [self.rootContent addSubview:_txtTitleField];
        
        RAC(self.viewModel.reqModel, newsTitle) = self.txtTitleField.rac_textSignal;
    }
}

- (void)initWithContentTextView
{
    CGRect frame = CGRectMake(15, self.txtTitleField.bottom + 20, kScreenW - 30, 130);
    _contentTextView = [[TYZPlaceholderTextView alloc] initWithFrame:frame];
    _contentTextView.placeholder = [AEStringExten localizedValueWithKey:@"发布你想说的吧…"];
    _contentTextView.placeholderFont = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    _contentTextView.backgroundColor = [UIColor colorWithHexString:@"#FAFAFA"];
    _contentTextView.placeholderColor = [UIColor colorWithHexString:@"#D9D9D9"];
    _contentTextView.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
//        _dynamicTextView.layer.masksToBounds = YES;
//        _dynamicTextView.layer.cornerRadius = 5;
//    _contentTextView.layer.borderColor = [UIColor colorWithHexString:@"#CCCCCC"].CGColor;
//    _contentTextView.layer.borderWidth = 1;
    _contentTextView.delegate = self;
    _contentTextView.returnKeyType = UIReturnKeyDone;
    [self.rootContent addSubview:_contentTextView];
    
    RAC(self.viewModel.reqModel, newsContent) = self.contentTextView.rac_textSignal;
}

/**
  动态发布的视图
 */
- (void)initWithImageVideoView
{
    if (!_imageVideoView)
    {
        CGRect frame = CGRectMake(15, self.contentTextView.bottom + 10, kScreenW - 15 * 2, self.viewModel.imageWH);
        _imageVideoView = [[EDSPublishDynamicImageVideoView alloc] initWithFrame:frame imageVideoNum:self.viewModel.addImageVideoNum imageWidth:self.viewModel.imageWH imageHeight:self.viewModel.imageWH];
        [self.rootContent addSubview:_imageVideoView];
//        self.imageVideoView.backgroundColor = [UIColor orangeColor];
        
        // 点击视频图片
        @weakify(self);
        _imageVideoView.touchVideoImgViewblock = ^{
//            @strongify(self);
//            [self actionPreviewvideo];
//            [SVProgressHUD showInfoWithStatus:@"333"];
        };
        // 删除图片
        _imageVideoView.deleteImageBlock = ^(NSInteger index) {
            @strongify(self);
            [self.viewModel.dataList removeObjectAtIndex:index];
            [self initWithImageVideoView];
        };
        
        // 点击添加图片或者视频
        [[_imageVideoView.btnAddImage rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            [self actionWithChoiceImageVideo];
        }];
    }
    
    _imageVideoView.height = self.viewModel.imagesHeight;
    
    // 图片
    self.imageVideoView.videoImgView.hidden = YES;
    NSInteger count = self.viewModel.dataList.count;
    
    for (int i=0; i<self.viewModel.addImageVideoNum; i++)
    {
        EDSPublishDynamicImageView *view = self.imageVideoView.imageList[i];
        if (i<count)
        {
            EDSImageVideoModel *model = self.viewModel.dataList[i];
            view.image = model.srcImage;
            view.hidden = NO;
            if (model.type == 1) {
                view.showPlayBtn = YES;
            } else {
                view.showPlayBtn = NO;
            }
        }
        else
        {
            view.hidden = YES;
        }
    }
//    debugLog(@"count=%zd; addImageVideoNum=%zd", count, self.viewModel.addImageVideoNum);
    if (count >= self.viewModel.addImageVideoNum)
    {
        self.imageVideoView.btnAddImage.hidden = YES;
    }
    else
    {
        EDSPublishDynamicImageView *view = self.imageVideoView.imageList[count];
        self.imageVideoView.btnAddImage.frame = view.frame;
        self.imageVideoView.btnAddImage.hidden = NO;
    }
    
//    self.height = _imageVideoView.bottom;
//    if (self.touchUpdateViewHeightBlock) {
//        self.touchUpdateViewHeightBlock();
//    }
    
}


/// 取消
- (void)actionWithCancel {
    [self clickedBack:nil];
}

/// 发布
- (void)actionWithPublish {
//    [SVProgressHUD showInfoWithStatus:@"发布"];
    if ([objectNull(self.viewModel.reqModel.newsTitle) isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"请输入标题！"];
        return;
    }
    
    if ([objectNull(self.viewModel.reqModel.newsContent) isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"请输入您想说的吧！"];
        return;
    }
    
    if (self.viewModel.dataList.count == 0) {
        [SVProgressHUD showInfoWithStatus:@"请添加图片！"];
        return;
    }
    [self.viewModel.reqModel.ossIds removeAllObjects];
    @weakify(self);
    if (self.viewModel.dataList.count == 0) {
        [self requestWithNewsAdd];
        return;
    }
    [self requestWithUploadImages:self.viewModel.dataList completion:^(EDSRespondDataEntity * _Nonnull respond) {
        @strongify(self);
        [self requestWithNewsAdd];
    }];
}

/// 添加新闻
- (void)requestWithNewsAdd {
    [SVProgressHUD showWithStatus:@"发布中..."];
    @weakify(self);
    [self.viewModel requestWithNewsAdd:^(EDSRespondDataEntity * _Nonnull respond) {
        @strongify(self);
        if (respond.code == EDS_NETWORK_SUCCESS) {
            [SVProgressHUD showSuccessWithStatus:@"发布成功了！"];
            [self clickedBack:nil];
            if (self.popResultBlock) {
                self.popResultBlock(nil);
            }
        } else {
            [SVProgressHUD showInfoWithStatus:@"发布失败，请稍后再试！"];
        }
    }];
}

/// 上传图片(其它)
/// - Parameter image: image description
- (void)requestWithUploadImages:(NSArray<EDSImageVideoModel *> *)images completion:(RequestCompletionBlock)completion {
    [SVProgressHUD showWithStatus:@"上传中......"];
//    self.viewModel.addImageModel = nil;
    NSMutableArray *mutList = [NSMutableArray arrayWithArray:images];
    EDSImageVideoModel *model = mutList.firstObject;
    [mutList removeFirstObject];
    @weakify(self);
    [self.viewModel requestWithUploadImage:model completion:^(EDSRespondDataEntity * _Nonnull respond) {
        @strongify(self);
        if (respond.code == EDS_NETWORK_SUCCESS) {
            
            if (mutList.count != 0) {
                [self requestWithUploadImages:mutList.copy completion:completion];
            } else {
                [SVProgressHUD showSuccessWithStatus:@"上传成功！"];
                if (completion) {
                    completion(respond);
                }
            }
        } else {
            if (mutList.count != 0) {
                [self requestWithUploadImages:mutList.copy completion:completion];
            } else {
                [SVProgressHUD showInfoWithStatus:@"上传失败，请稍后再试！"];
                if (completion) {
                    completion(respond);
                }
            }
        }
    }];
}

/// 选择图片
- (void)actionWithChoiceImageVideo {
    [self clickedAddImage];
}

/**
 添加图片
 */
- (void)clickedAddImage
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    @weakify(self);
    // 拍照和视频
    UIAlertAction *videoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self);
        [self openPicOrVideoWithSign];
    }];
    UIAlertAction *pictureAction = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self);
//        self.viewModel.photoType = 0;
        [self photoAlbumImageVideo];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:videoAction];
    [alertController addAction:pictureAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)openPicOrVideoWithSign
{
    UIImagePickerController *imagePicker = nil;
    //相机
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.allowsEditing = YES;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePicker.mediaTypes =  [[NSArray alloc] initWithObjects: @"public.image", nil];
        imagePicker.delegate = self;
    }
    if (imagePicker)
    {
        if (@available(iOS 11.0, *))
        {
            [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentAutomatic];
        }
        [TYZJumpVCManager presentBaseVC:self presentVC:imagePicker completion:nil];
    }
}

/**
 从相册获取图片或则视频
 */
- (void)photoAlbumImageVideo
{
    @weakify(self);
    //相册权限
    [AuthorityManager getPhotoAuthorityWithAgreeAuthority:^(BOOL isAuthorized) {
        @strongify(self);
        if (isAuthorized)
        {
            @weakify(self);
            void(^block)(NSMutableArray *selectPhotoList, int libType) = ^(NSMutableArray *selectPhotoList, int libType) {
                @strongify(self);
                self.viewModel.libType = libType;
                self.viewModel.imageSize = [self.viewModel getImageSize:selectPhotoList.firstObject];
                [self.viewModel.dataList addObjectsFromArray:selectPhotoList];
                NSArray *tmpList = [self.viewModel.dataList copy];
                if (tmpList.count > self.viewModel.addImageVideoNum)
                {// 当出现大雨9个的时候，就只要9个
                    [self.viewModel.dataList removeAllObjects];
                    [self.viewModel.dataList addObjectsFromArray:[tmpList subarrayWithRange:NSMakeRange(0, self.viewModel.addImageVideoNum)]];
                }
                
                [self initWithImageVideoView];
            };
            // isSelectImage yes 表示只选择图片；NO表示 选择图片和视频
            NSDictionary *param = @{@"selectPhotoNumType":@(1), @"photoNum":@(self.viewModel.dataList.count), @"isSelectImage":@(YES), @"selectPhotoBlock":block, @"ispush":@(NO)};
            DoImagePickerViewController *imagePickerVC = [[DoImagePickerViewController alloc] init];
            imagePickerVC.selectPhotoNumType = [param[@"selectPhotoNumType"] intValue];
            imagePickerVC.photoNum = [param[@"photoNum"] integerValue];
            imagePickerVC.isSelectImage = [param[@"isSelectImage"] boolValue];
            imagePickerVC.selectPhotoBlock = block;
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:imagePickerVC];
            [TYZJumpVCManager presentBaseVC:self presentVC:nav completion:nil];
        }
    }];

}

#pragma mark - UINavigationControllerDelegate,UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    if (@available(iOS 11.0, *))
    {
        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }
    if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:@"public.image"])
    {
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        CGSize imgSize = image.size;
                
        NSData *imgData = UIImageJPEGRepresentation(image, 0.8);
        UIImage *upImage = [[UIImage alloc] initWithData:imgData];
        EDSImageVideoModel *imgModel = [EDSImageVideoModel new];
        imgModel.srcImage = upImage;
        imgModel.type = 0;
        
        
        [self.viewModel.dataList addObjectsFromArray:@[imgModel]];
        NSArray *tmpList = [self.viewModel.dataList copy];
        if (tmpList.count > self.viewModel.addImageVideoNum)
        {// 当出现大雨9个的时候，就只要9个
            [self.viewModel.dataList removeAllObjects];
            [self.viewModel.dataList addObjectsFromArray:[tmpList subarrayWithRange:NSMakeRange(0, self.viewModel.addImageVideoNum)]];
        }
        [self initWithImageVideoView];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    if (@available(iOS 11.0, *))
    {
        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }
}


#pragma mark - UITextViewDelegate
// 在输入时触发，包括输入和删除字符串，甚至是n粘贴过来的，当然下面的方法也同样会触发，
// 返回值，一般用于控制输入
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"])
    {
        // 返回NO，表示键盘失效
        [textView resignFirstResponder];
        return NO;
    }
    
    // 获取标记文本，找到是否处于中文的连输入状态
    // 通过markedTextRange获取到当前拼字的range范围，并将这个range转为UITextPosition
    UITextRange *selectdRange = [textView markedTextRange];
    UITextPosition *pos = [textView positionFromPosition:selectdRange.start offset:0];
    
    if (selectdRange && pos)
    {
        // 找到拼写的起始位置
        NSInteger startOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectdRange.start];
        NSInteger endOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectdRange.end];
        NSRange offsetRange = NSMakeRange(startOffset, endOffset - startOffset);
        if (offsetRange.location < kDynamicTextMaxNum)
        {
            return YES;// 允许输入
        }
        return NO;// 不允许输入
    }
    
    NSString *comcatstr = [textView.text stringByReplacingCharactersInRange:range withString:text];
    //    debugLog(@"comcatstr=%@", comcatstr);
    NSInteger caninputlen = kDynamicTextMaxNum - comcatstr.cLength;
    if (caninputlen >= 0)
    {
        return YES;
    }
    else
    {
        //        debugLog(@"else--%ld", caninputlen);
        NSInteger len = text.cLength + caninputlen;
        NSRange rg = {0, MAX(len, 0)};
        //        debugLog(@"len=%d; lent=%d", len, rg.length);
        if (rg.length > 0)
        {
            NSString *s = [text substringWithRange:rg];
            [textView setText:[textView.text stringByReplacingCharactersInRange:range withString:s]];
//            self.dynamicTextNumLabel.text = [NSString stringWithFormat:@"%d/%ld", 0, (long)kDynamicTextMaxNum];
        }
        return NO;
    }
}

// 对变化后的文本做调整
- (void)textViewDidChange:(UITextView *)textView
{
    // 获取高亮部分
    UITextRange *selectedRange = [textView markedTextRange];
    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];
    // 如果在变化中是高亮部分在变，则不需要计算字符
    if (selectedRange && pos)
    {
        return;
    }
    
    NSString *nstextContent = textView.text;
    NSInteger existTextNum = nstextContent.cLength;
    if (existTextNum > kDynamicTextMaxNum)
    {
        // h截取到最大位置的字符
        NSString *s = [nstextContent substringToIndex:kDynamicTextMaxNum];
        [textView setText:s];
    }
    // 不显示负数
//    self.dynamicTextNumLabel.text = [NSString stringWithFormat:@"%ld/%ld", (long)existTextNum, (long)kDynamicTextMaxNum];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.view endEditing:YES];
    return YES;
}


@end
